package com.gonsin.gview.common.auth;

import com.gonsin.base.ResponseResult;
import com.gonsin.gview.common.utils.SessionKeys;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * 自定义一个切面类，利用aspect实现切入所有方法
 *
 * @author spc
 */
@Aspect
@Component
@Slf4j
public class WebApiAop {

    @Autowired
    private JwtConfig jwtConfig;

    @Around("execution(@com.gonsin.gview.common.auth.WebApi * *(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
        Method method = joinPointObject.getMethod();
        WebApi webApi = method.getAnnotation(WebApi.class);

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();


        HttpSession session = request.getSession();
        if (webApi == null) {
            return pjp.proceed();
        }
        if (webApi.login()) {
            return pjp.proceed();
        }


        String userKey = (String) session.getAttribute(SessionKeys.USER_KEY);
        if(StringUtils.isNotEmpty(userKey)){
            return pjp.proceed();
        }

        return ResponseResult.simpleResult(BaseResultCodes.USER_TIMEOUT.getValue(), "登录超时或未登录");

    }

}